package sicnu.cs.aps.common.util;

import org.apache.logging.log4j.util.Strings;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class CollectionUtil {
    public static TreeSet<? extends GrantedAuthority> toTreeSet(Collection<? extends GrantedAuthority> authorities) {
        return authorities.stream().collect(
                Collectors.toCollection(
                        () -> new TreeSet<>(
                                Comparator.comparing(GrantedAuthority::getAuthority)
                        )
                )
        );
    }

    public static List<?> convertObjectToList(Object obj) {
        List<?> list = new ArrayList<>();
        if (obj.getClass().isArray()) {
            list = Arrays.asList((Object[]) obj);
        } else if (obj instanceof Collection) {
            list = new ArrayList<>((Collection<?>) obj);
        }
        return list;
    }

    /**
     * 合并列表（合并后以|分割）
     *
     * @param list 待合并的列表
     * @return 合并后字符串
     */
    public static String combineList(List<?> list) {
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }
        var sb = new StringBuilder();
        list.forEach(i -> sb.append(i).append("|"));
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 拆分字符串（保留空）
     *
     * @param value
     * @return
     */
    public static List<String> separateString(String value) {
        if (Strings.isEmpty(value)) {
            return Collections.emptyList();
        }
        final String[] split = value.split("\\|");
        var rs = Arrays.stream(split).collect(Collectors.toList());

        // 找出被split吃掉的最后几个空
        if (value.charAt(value.length() - 1) == '|') {
            int idx = value.length() - 1;
            while (value.charAt(idx) == '|') idx--;
            while (idx++ < value.length() - 1 - 1) rs.add("");
        }

        return rs;
    }

    /**
     * 拆分字符串（过滤掉空）
     *
     * @param value
     * @return
     */
    public static List<String> separateStringExcludeEmpty(String value) {
        if (Strings.isEmpty(value)) {
            return Collections.emptyList();
        }
        return Arrays.stream(value.split("\\|"))
                .filter(s -> s.length() > 0)
                .collect(Collectors.toList());
    }

//    public static List<Permission> permissionSetToTree(Set<Permission> set) {
//        List<Permission> permissionList = new ArrayList<>();
//        set.forEach(p -> {
//            if (p.getParentId() == 0) {
//                permissionList.add(p);
//            } else {
//                permissionList.forEach(p2 -> {
//                    if (p.getParentId().equals(p2.getId())) {
//                        p2.getChildren().add(p);
//                    }
//                });
//            }
//        });
//        return permissionList;
//    }

    /**
     * 从list中随机抽取元素
     *
     * @param list
     * @param n
     * @return void
     */
    public static <T> List<T> createRandomList(List<T> list, int n) {
        // TODO 有空修改算法，使用 Shuffle 算法（效率提升应该挺客观的）
        Set<Integer> record = new HashSet<>();
        List<T> listNew = new ArrayList<>();
        if (list.size() <= n) {
            return list;
        } else {
            while (record.size() < n) {
                int random = (int) (Math.random() * list.size());
                if (!record.contains(random)) {
                    record.add(random);
                    listNew.add(list.get(random));
                }
            }
            return listNew;
        }
    }
}
